<template>
    <div class="container">
        <div class="top-header van-hairline--bottom">
            <input :key="'filter'" type="text" v-model="filter_city" v-if="!showCity" class="city-filter"
                   placeholder="输入城市名称"/>
            <div :key="'city-text'" class="city-text" v-if="showCity" @click="changeShowCity()">
                <p class="label">{{from != 'taxi' ? area : location.city}}<i v-if="from != 'taxi'"
                                                                             class="iconfont icon-bottom icon-arrow"></i>
                </p>
            </div>
            <div class="line">
            </div>
            <input type="text" v-model="keyword"
                   @input="searchChange" class="search-wrapper" :placeholder="searchPlaceholder"/>
            <button class="btn-cancel" @click="$router.goBack()">取消</button>
        </div>
        <div :key="'scroll-cities'" class="scroll-cities" v-if="!showCity">
            <div class="location-city van-hairline--bottom">
                当前定位城市:{{location.city}}
            </div>
            <div v-bind:key="`letter-city-${index}`" v-for="(item,index) in cities" class="city-wrapper-item">
                <div class="city-letter" v-show="isFirstLetter(item) == index">
                    {{item.letter}}
                </div>
                <div class="city-group">
                    <div class="city-title" @click="cityItemClick(item,index)">
                        {{item.name}} <i v-if="item.children.length == 0"
                                         class="iconfont icon-bottom icon-right"></i>
                        <i class="iconfont icon-bottom icon-toggle" v-else
                           :class="openIndex == index ? 'up':''"></i>
                    </div>
                    <div class="children-wrapper" v-show="item.children.length > 0 && openIndex == index">
                        <div class="child-item" @click="childItemClick(sub,item,index2)"
                             v-bind:key="`sub-item-${index2}`"
                             v-for="(sub,index2) in item.children">
                            {{sub}}
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div :key="'scroll-picker'" class="scroll-picker" v-if="showCity">
            <div class="poi-item van-hairline--bottom" v-bind:key="`poi-item-${index}`"
                 @click="onPoiClick(item,index)" v-for="(item,index) in pois">
                <i class="iconfont icon-address"></i>
                <div class="text-wrapper">
                    <div class="title">
                        {{item.name}}
                    </div>
                    <div class="address">
                        {{area}}{{item.address}}
                    </div>
                </div>

            </div>
        </div>

    </div>
</template>

<script>
    /* eslint-disable no-undef,no-console */

    import api from '../net/api'
    import url from '../net/url'
    import pinyin from 'tiny-pinyin';


    export default {
        name: "CityPicker",
        data() {
            return {
                keyword: "",
                flag: false,
                raws: [],
                data: [],
                area: '',
                showCity: false,
                openIndex: -1,
                pois: [],
                filter_city: '',
                parent: ""
            }
        },

        filters: {
            sampleLetter(value) {
                return value.replace("市", '')
            }
        },

        methods: {
            changeShowCity() {
                if (this.from == 'taxi') {
                    return
                }
                this.showCity = false
            },
            isFirstLetter(item) {
                for (let i = 0; i < this.cities.length; i++) {
                    let city = this.cities[i];
                    if (city.letter == item.letter) {
                        return i;
                    }
                }
            },
            onPoiClick(item, index) {
                let parent = this.parent ? this.parent : '';
                let area = this.area ? this.area : this.location.city;

                let picker_item = {
                    lat: item.location.lat,
                    lng: item.location.lng,
                    address: `${parent}${area}${item.address}`,
                    area: area,
                    parent: parent
                }
                window.eventBus.$emit('onCityPickerChoose', picker_item, this.from, this.type);
                this.$router.goBack();
            },
            searchChange() {
                let value = this.keyword
                setTimeout(() => {
                    if (value == this.keyword) {
                        console.log(this.keyword)
                        this.loadPois();
                    }
                }, 300)
            },

            cityItemClick(item, index) {
                if (this.openIndex == index) {
                    this.openIndex = -1;
                } else {
                    this.openIndex = index;
                }
                if (item.children.length === 0) {
                    this.area = item.name;
                    this.parent = item.name;
                    this.showCity = true;
                    this.loadPois();
                }
            },
            childItemClick(item, parent, index) {
                this.area = item;
                this.parent = parent.name;

                this.showCity = true;
                this.loadPois();
            },

            loadCities() {
                api.get(url.LOAD_CITY_DATA).then(res => {

                    this.raws = res.data.map(item => {
                        item.letter = pinyin.convertToPinyin(item.name).charAt(0)
                        return item;
                    })
                    this.raws.sort((a, b) => {
                        if (a.letter === b.letter) {
                            return 0;
                        }
                        if (typeof a.letter === typeof b.letter) {
                            return a.letter < b.letter ? -1 : 1;
                        }
                        return typeof a.letter < typeof b.letter ? -1 : 1;
                    })
                }).catch(error => {

                })
            },
            loadPois() {
                let self = this;
                setTimeout(() => {
                    let area = self.area ? self.area : self.location.city
                    let placeSearch = new AMap.PlaceSearch({
                        // city 指定搜索所在城市，支持传入格式有：城市名、citycode和adcode
                        city: area,
                        citylimit: true,
                        type: '餐饮服务|购物服务|生活服务|住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|' +
                            +'交通设施服务|金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施'
                    });
                    placeSearch.search(self.keyword, (status, result) => {
                        console.log(result);
                        self.pois = result.poiList.pois;
                    })
                }, 0)

            }
        },

        beforeRouteEnter(to, from, next) {


            next(vm => {
                // 通过 `vm` 访问组件实例
                let showCity = vm.$route.query.showCity;
                let area = vm.$route.query.area;
                let parent = vm.$route.query.parent;
                if (typeof(showCity) == 'string') {
                    showCity = showCity == 'false' ? false : true
                }
                vm.showCity = showCity;
                vm.area = area ? area : '';
                vm.parent = parent ? parent : '';
                if (vm.area) {
                    vm.loadPois();
                }
            })

        },

        beforeRouteLeave(to, from, next) {
            // 导航离开该组件的对应路由时调用
            // 可以访问组件实例 `this`
            console.log(to)
            next();
        },

        computed: {
            cities() {
                return this.raws.filter((item) => {
                    if (item.name.indexOf(this.filter_city) !== -1) {
                        return true
                    }
                    let has = false;
                    item.children.forEach(child => {
                        if (child.indexOf(this.filter_city) !== -1) {
                            has = true
                        }
                    });
                    return has;
                })
            },

            type() {
                return this.$route.query.type ? this.$route.query.type : 'start'
            },
            from() {
                return this.$route.query.from ? this.$route.query.from : 'share'
            },


            location() {
                let location = this.$store.state.location
                if (location.city) {
                    if (this.from == 'taxi') {
                        this.loadPois();
                    }

                }
                return location
            },
            searchPlaceholder() {
                if (this.from == 'share') {
                    switch (this.type) {
                        case 'start':
                            return '从哪儿出发？'
                        case 'target':
                            return '去哪儿？'

                        default:
                            return '去哪儿？'

                    }
                } else if (this.from == 'express') {
                    switch (this.type) {
                        case 'start':
                            return '从哪儿寄？'
                        case 'target':
                            return '寄到哪儿？'
                        default:
                            return '寄到哪儿？'

                    }
                } else {
                    switch (this.type) {
                        case 'start':
                            return '从哪儿出发？'
                        case 'target':
                            return '去哪儿？'
                        default:
                            return '去哪儿？'

                    }
                }
            }
        },
        mounted() {
            this.loadCities();
        }
    }
</script>

<style scoped lang="less">
    .top-header {
        height: 50px;
        display: flex;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        flex-direction: row;
        align-items: center;
        box-sizing: border-box;
        background: #fff;
        z-index: 101;
        .city-filter {
            width: 100px;
            height: 40px;
            color: #444;
            flex-shrink: 0;
            box-sizing: border-box;
            outline: none;
            font-size: 14px;
            border: none;
            margin-left: 16px;
        }
        .city-text {
            width: 80px;
            min-width: 80px;
            height: 40px;
            line-height: 40px;
            font-size: 14px;
            margin: 0;
            position: relative;
            text-align: center;
            .label {
                font-size: 14px;
                margin: 0;
                .icon-arrow {
                    /*right: 10px;*/
                    margin-left: 4px;
                    /*position: absolute;*/
                }
            }
        }
        .search-wrapper {
            flex: 1;
            height: 40px;
            margin-left: 16px;
            font-size: 14px;
            color: #444;
            box-sizing: border-box;
            outline: none;
            border: none;
            transition: all 0.3s ease-in;

        }
        .line {
            width: 1px;
            height: 24px;
            flex-shrink: 0;
            background: #e0e0e0;
        }
        .btn-cancel {
            color: red;
            background: transparent;
            outline: none;
            border: none;
            width: 54px;
            &:active {
                background: #f2f2f2;
            }
        }

    }

    .scroll-picker {
        padding-top: 50px;
        .poi-item {
            height: 60px;
            display: flex;
            align-items: center;
            flex-direction: row;
            &:active {
                background: darken(#fff, 5%);
            }
            .icon-address {
                margin-left: 8px;
                margin-right: 10px;
                font-size: 18px;
            }
            .text-wrapper {
                flex: 1;
                flex-direction: column;
                display: flex;
                .title {
                    font-size: 14px;
                    color: #444;
                }
                .address {
                    font-size: 14px;
                    color: #888;
                }
            }

        }
    }

    .scroll-cities {
        padding-top: 50px;
        font-size: 14px;
        .location-city {
            height: 40px;
            box-sizing: border-box;
            padding-left: 16px;
            padding-right: 16px;
            line-height: 40px;
        }
        .city-wrapper-item {
            .city-letter {
                font-size: 14px;
                line-height: 24px;
                box-sizing: border-box;
                padding-left: 10px;
                padding-right: 10px;
                background: #f2f2f2;
            }
            .city-group {
                .city-title {
                    height: 40px;
                    background: #fff;
                    line-height: 40px;
                    box-sizing: border-box;
                    padding: 0 10px;
                    display: flex;
                    flex-direction: row;
                    &:active {
                        background: #f2f2f2;
                    }
                    .icon-right {
                        margin-left: auto;
                        transform: rotate(-90deg);
                    }
                    .icon-toggle {
                        margin-left: 8px;
                        transition: all 0.3s ease-in-out;
                        &.up {
                            transform: rotate(180deg);
                        }
                    }
                }
                .children-wrapper {
                    background: #f2f2f2;
                    padding: 10px;
                    display: flex;
                    flex-direction: row;
                    flex-wrap: wrap;
                    .child-item {
                        width: calc(33.3333% - 16px);
                        box-sizing: border-box;
                        margin-right: 16px;
                        border-radius: 5px;
                        border: solid 1px #e0e0e0;
                        text-align: center;
                        background: #fff;
                        height: 30px;
                        line-height: 30px;
                        margin-bottom: 10px;
                        &:nth-child(3n) {
                            margin-right: 0;
                        }
                        &:active {
                            background: darken(#fff, 5%);
                        }
                    }
                }
            }
        }
    }
</style>